﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using SFML.Window;

namespace Theta.Components
{
    public class PhysicsEnabledComponent : BaseComponent
    {
        public Body Body { get; set; }
        RenderableComponent _parentRender;

        public Vector2f Position
        {
            get { return Converter.ToVector2f(Converter.ToPixels(Body.Position)); }
            set { Body.Position = Converter.ToMeters(Converter.ToVector2(value)); }
        }
        
        public PhysicsEnabledComponent(Body body)
        {
            Body = body;
        }

        protected override void OnAdd(Entities.Entity parent)
        {
            RenderableComponent r = parent.GetComponent<RenderableComponent>();

            if (r == null)
                throw new ArgumentException(
                    "A RenderableComponent component must be attach to the entity before attaching a PhysicsEnabledComponent.");

            _parentRender = r;
            Body.Position = Converter.ToVector2(Converter.ToMeters(r.Position));
            Body.Rotation = Converter.ToMeters(r.Rotation);
            //r.Origin = new Vector2f(r.Image.Width / 2f, r.Image.Width / 2f);
        }

        protected override void OnRemove()
        {
            Body.Dispose();
        }

        public override void Update(TimeSpan elapsedTime)
        {
            _parentRender.Position = Converter.ToVector2f(Converter.ToPixels(Body.Position));
            _parentRender.Rotation = Converter.ToPixels(Body.Rotation);
        }
    }
}
